package com.ymttest.business.service.shenqi;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONObject;

import com.shop2cn.iapi.member.parameter.BriefMemberInfoBean;
import com.shop2cn.iapi.member.parameter.BriefMemberInfoResp;
import com.shop2cn.iapi.member.parameter.CreateMemberBean;
import com.shop2cn.iapi.member.service.BriefMemberInfoCall;
import com.shop2cn.iapi.sqdistributor.parameter.request.AuditDistributorApplyReq;
import com.shop2cn.iapi.sqdistributor.parameter.request.BindDistributorConsumerRelationReq;
import com.shop2cn.iapi.sqdistributor.parameter.request.BindMerchantRootDistributorReq;
import com.shop2cn.iapi.sqdistributor.parameter.request.DeleteDistributorAndConsumerRelationReq;
import com.shop2cn.iapi.sqdistributor.parameter.request.DistributorApplyReq;
import com.shop2cn.iapi.sqdistributor.parameter.request.ProductCategoryRateInsertReq;
import com.shop2cn.iapi.sqdistributor.parameter.request.SaveMerchantDistributorInviteConfigReq;
import com.shop2cn.iapi.sqdistributor.parameter.request.SaveProductCommissionReq;
import com.shop2cn.iapi.sqdistributor.parameter.request.SetAgencyDistributorConfigReq;
import com.shop2cn.iapi.sqdistributor.parameter.request.SetDistributionAgencyConfigReq;
import com.shop2cn.iapi.sqdistributor.parameter.request.SetDistributionConfigReq;
import com.shop2cn.iapi.sqdistributor.parameter.request.UpdateDistributorInfoReq;
import com.shop2cn.iapi.sqdistributor.parameter.request.pojo.AgencyCategoryCommissionRateVo;
import com.shop2cn.iapi.sqdistributor.parameter.request.pojo.AgencySubDistributorCommisionRateVo;
import com.shop2cn.iapi.sqdistributor.parameter.request.pojo.DistributionAgencyLevelCommissionConfigVo;
import com.shop2cn.iapi.sqdistributor.parameter.request.pojo.DistributorCommission;
import com.shop2cn.iapi.sqdistributor.parameter.request.pojo.DistributorLevelCommissionConfigVo;
import com.shop2cn.iapi.sqdistributor.parameter.request.pojo.PartnerCommission;
import com.shop2cn.iapi.sqdistributor.parameter.request.pojo.ProductCategoryCommissionRateVo;
import com.shop2cn.iapi.sqdistributor.parameter.request.pojo.ProductCommission;
import com.shop2cn.iapi.sqdistributor.service.AuditDistributorApplyCall;
import com.shop2cn.iapi.sqdistributor.service.BindDistributorConsumerRelationCall;
import com.shop2cn.iapi.sqdistributor.service.BindMerchantRootDistributorCall;
import com.shop2cn.iapi.sqdistributor.service.DeleteDistributorAndConsumerRelationCall;
import com.shop2cn.iapi.sqdistributor.service.DistributorApplyCall;
import com.shop2cn.iapi.sqdistributor.service.ProductCategoryRateInsertCall;
import com.shop2cn.iapi.sqdistributor.service.SaveMerchantDistributorInviteConfigCall;
import com.shop2cn.iapi.sqdistributor.service.SaveProductCommissionCall;
import com.shop2cn.iapi.sqdistributor.service.SetAgencyDistributorConfigCall;
import com.shop2cn.iapi.sqdistributor.service.SetDistributionAgencyConfigCall;
import com.shop2cn.iapi.sqdistributor.service.SetDistributionConfigCall;
import com.shop2cn.iapi.sqdistributor.service.UpdateDistributorInfoCall;
import com.ymatou.iapi.dguser.parameter.UserCreateBean;
import com.ymatou.iapi.godmch.parameter.getAllChainShopIdListBean;
import com.ymatou.iapi.godmch.parameter.setBizConfigBean;
import com.ymatou.iapi.godmch.service.getAllChainShopIdListCall;
import com.ymatou.iapi.godmch.service.setBizConfigCall;
import com.ymt.base.YmatouEasyCall;
import com.ymt.core.tool.Logger;
import com.ymttest.business.service.DGUserCallService;
import com.ymttest.business.service.GodMemberService;
import com.ymttest.business.service.OrderCallService;
import com.ymttest.business.service.shenqi.bean.ShenqiUserSet;
import com.ymttest.database.model.sqdistributor.DistributorApply;
import com.ymttest.database.model.sqdistributor.DistributorRelation;
import com.ymttest.database.sqlwapper.sqdistributor.DistributorApplyWrapper;
import com.ymttest.database.sqlwapper.sqdistributor.DistributorConsumerRelationWrapper;
import com.ymttest.database.sqlwapper.sqdistributor.DistributorRelationWrapper;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;

public class SqDistributorService {

	public static int cpsExpirationTime = 48;
	private static DistributorRelationWrapper distributorRelationWrapper = new DistributorRelationWrapper();

	/**
	 * 创建分销员申请单，并返回申请单id
	 * 
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static Long getDistributorApplyId(
			DistributorApplyReq distributorApplyReq)
			throws ClientProtocolException, IOException {

		DistributorApplyCall distributorApplyCall = new DistributorApplyCall();

		distributorApplyCall.setData(distributorApplyReq);
		distributorApplyCall.callService();

		DistributorApplyWrapper distributorApplyWrapper = new DistributorApplyWrapper();

		DistributorApply distributorApply = distributorApplyWrapper
				.selectByApplyUserIdAndReferrerId(
						distributorApplyReq.getDistributorId(),
						distributorApplyReq.getInviterId());

		if (distributorApply != null)
			return distributorApply.getId();
		else
			return 0L;
	}

	/**
	 * 审核分销员申请单成功，并返回id
	 * 
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static Long auditDistributorApplySuccess(Long merchantId)
			throws ClientProtocolException, IOException {

		DistributorApplyReq distributorApplyReq = DistributorApplyReq
				.createStandardDistributorApply(merchantId);
		Long id = SqDistributorService
				.getDistributorApplyId(distributorApplyReq);

		AuditDistributorApplyReq auditDistributorApplyReq = new AuditDistributorApplyReq();
		AuditDistributorApplyCall auditDistributorApplyCall = new AuditDistributorApplyCall();

		auditDistributorApplyReq.setAuditorId((long) TestDataManager
				.getRandomIntNum(5));
		auditDistributorApplyReq.setId(id);
		auditDistributorApplyReq.setPass(true);
		auditDistributorApplyReq.setRemark(TestDataManager.randomStr(5));

		auditDistributorApplyCall.setData(auditDistributorApplyReq);
		auditDistributorApplyCall.callService();

		DistributorRelation distributorRelation = distributorRelationWrapper
				.selectByMerchantIdAndDistributorId(
						distributorApplyReq.getMerchantId(),
						distributorApplyReq.getDistributorId());

		return distributorRelation.getId();
	}

	/**
	 * 绑定分销员与消费者的临时关系
	 * 
	 * @param userId
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static BindDistributorConsumerRelationReq bindDistributorConsumerTempRelation(
			Long userId) throws ClientProtocolException, IOException {

		BindDistributorConsumerRelationReq bindDistributorConsumerRelationReq = new BindDistributorConsumerRelationReq();
		BindDistributorConsumerRelationCall bindDistributorConsumerRelationCall = new BindDistributorConsumerRelationCall();

		bindDistributorConsumerRelationReq.setDistributorId(501565931L);
		bindDistributorConsumerRelationReq
				.setMerchantId(ShenqiUserSet.tempRelationMerchantId);
		bindDistributorConsumerRelationReq.setUserId(userId);
		bindDistributorConsumerRelationReq.setUserName(TestDataManager
				.getChineseName());
		bindDistributorConsumerRelationReq.setUserPhone(TestDataManager
				.getPhoneNum());
		bindDistributorConsumerRelationReq.setOpenId(TestDataManager.randomStr(10));

		bindDistributorConsumerRelationCall
				.setData(bindDistributorConsumerRelationReq);
		bindDistributorConsumerRelationCall.callService();

		return bindDistributorConsumerRelationReq;
	}

	/**
	 * 绑定分销员与消费者的永久关系
	 * 
	 * @param userId
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void bindDistributorConsumerForeverRelation(Long userId)
			throws ClientProtocolException, IOException {

		BindDistributorConsumerRelationReq bindDistributorConsumerRelationReq = new BindDistributorConsumerRelationReq();
		BindDistributorConsumerRelationCall bindDistributorConsumerRelationCall = new BindDistributorConsumerRelationCall();

		bindDistributorConsumerRelationReq.setDistributorId(1232663038L);
		bindDistributorConsumerRelationReq.setMerchantId(500861041L);
		bindDistributorConsumerRelationReq.setUserId(userId);
		bindDistributorConsumerRelationReq.setUserName(TestDataManager
				.getChineseName());
		bindDistributorConsumerRelationReq.setUserPhone(TestDataManager
				.getPhoneNum());
		bindDistributorConsumerRelationReq.setOpenId(TestDataManager.randomStr(10));

		bindDistributorConsumerRelationCall
				.setData(bindDistributorConsumerRelationReq);
		bindDistributorConsumerRelationCall.callService();
	}

	public static BindDistributorConsumerRelationReq bindDistributorConsumerRelation(Long userId,
			Long merchantId, Long distributorId)
			throws ClientProtocolException, IOException {

		BindDistributorConsumerRelationReq bindDistributorConsumerRelationReq = new BindDistributorConsumerRelationReq();
		BindDistributorConsumerRelationCall bindDistributorConsumerRelationCall = new BindDistributorConsumerRelationCall();

		bindDistributorConsumerRelationReq.setDistributorId(distributorId);
		bindDistributorConsumerRelationReq.setMerchantId(merchantId);
		bindDistributorConsumerRelationReq.setUserId(userId);
		bindDistributorConsumerRelationReq.setUserName("autotest"
				+ TestDataManager.randomStr(8));
		bindDistributorConsumerRelationReq.setUserPhone(TestDataManager
				.getPhoneNum());
		bindDistributorConsumerRelationReq.setOpenId(TestDataManager.randomStr(10));

		bindDistributorConsumerRelationCall
				.setData(bindDistributorConsumerRelationReq);
		bindDistributorConsumerRelationCall.callService();
		
		return bindDistributorConsumerRelationReq;
	}

	public static void deleteDistributorConsumerRelation(Long id)
			throws ClientProtocolException, IOException {

		DeleteDistributorAndConsumerRelationReq deleteDistributorAndConsumerRelationReq = new DeleteDistributorAndConsumerRelationReq();
		DeleteDistributorAndConsumerRelationCall deleteDistributorAndConsumerRelationCall = new DeleteDistributorAndConsumerRelationCall();

		deleteDistributorAndConsumerRelationReq.setId(id);

		deleteDistributorAndConsumerRelationCall
				.setData(deleteDistributorAndConsumerRelationReq);
		deleteDistributorAndConsumerRelationCall.callService();
	}

	/**
	 * 构建分销员关系
	 * 
	 * @param merchantId
	 * @param level
	 * @param num
	 * @param parent_distributor_id
	 * @return
	 */
	public static List<Long> buildSqDistributorRelation(long merchantId,
			int level, int num, long parent_distributor_id) {
		try {

			if (level == 0)
				distributorRelationWrapper
						.deleteDistributorRelationByMerchantId(merchantId);

			DistributorRelation distributorRelation = null;
			long distributorId = 0L;
			List<Long> distributorList = new ArrayList<Long>();

			for (int i = 0; i < num; i++) {

				distributorRelation = new DistributorRelation();

				if (i == 0 && level == 0) {

					distributorRelation.setDistributor_id(merchantId);
					distributorId = merchantId;

				} else {

					int userId = new OrderCallService().createNewUser();

					distributorId = userId;
					distributorRelation.setDistributor_id(distributorId);
				}

				distributorRelation.setMerchant_id(merchantId);
				distributorRelation.setDistributor_name("autotest"
						+ TestDataManager.randomStr(8));
				distributorRelation.setDistributor_phone(TestDataManager
						.getPhoneNum());
				distributorRelation.setDistributor_level_index(level);
				distributorRelation.setDistributor_status(0);
				distributorRelation
						.setParent_distributor_id(parent_distributor_id);
				distributorRelation.setAdd_time(YMTDateUtil.getDate());
				distributorRelation.setUpdate_time(YMTDateUtil.getDate());

				parent_distributor_id = distributorId;

				distributorRelationWrapper.insert(distributorRelation);

				distributorList.add(distributorId);
			}

			return distributorList;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ArrayList<Long>();
		}
	}

	public static Long buildSingleSqDistributorRelation(long merchantId,
			int level, long parent_distributor_id, Long distributorId, int distributorType) {
		try {

			DistributorRelation distributorRelation = null;

			distributorRelation = new DistributorRelation();

			distributorRelation.setDistributor_id(distributorId);

			distributorRelation.setMerchant_id(merchantId);
			distributorRelation.setDistributor_name("autotest"
					+ TestDataManager.randomStr(8));
			distributorRelation.setDistributor_phone(TestDataManager
					.getPhoneNum());
			distributorRelation.setDistributor_level_index(level);
			distributorRelation.setDistributor_status(0);
			distributorRelation.setParent_distributor_id(parent_distributor_id);
			distributorRelation.setAdd_time(YMTDateUtil.getDate());
			distributorRelation.setUpdate_time(YMTDateUtil.getDate());
			distributorRelation.setDistributor_type(distributorType);

			parent_distributor_id = distributorId;

			distributorRelationWrapper.insert(distributorRelation);

			return distributorId;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public static List<Long> buildSqDistributorAgencyRelation(long merchantId,
			int level, int num, long parent_distributor_id, int agencyType) {
		try {

//			if (level == 0)
//				distributorRelationWrapper
//						.deleteDistributorRelationByMerchantId(merchantId);

			DistributorRelation distributorRelation = null;
			long distributorId = 0L;
			List<Long> distributorList = new ArrayList<Long>();
			
//			distributorRelation = new DistributorRelation();
//			
//			distributorRelation.setDistributor_id(merchantId);
//			distributorRelation.setMerchant_id(merchantId);
//			distributorRelation.setDistributor_name("autotest"
//					+ TestDataManager.randomStr(8));
//			distributorRelation.setDistributor_phone(TestDataManager
//					.getPhoneNum());
//			distributorRelation.setDistributor_level_index(level);
//			distributorRelation.setDistributor_status(0);
//			distributorRelation
//					.setParent_distributor_id(0L);
//			distributorRelation.setDistributor_type(0);
//			distributorRelation.setAdd_time(YMTDateUtil.getDate());
//			distributorRelation.setUpdate_time(YMTDateUtil.getDate());
//			
//			distributorRelationWrapper.insert(distributorRelation);

			// 第一个人是分销机构/CPS，后面的人都是该分销机构/CPS下的分销员
			for (int i = 0; i < num; i++) {

				distributorRelation = new DistributorRelation();

				int userId = new OrderCallService().createNewUser();

				distributorId = userId;
				distributorRelation.setDistributor_id(distributorId);

				distributorRelation.setMerchant_id(merchantId);
				distributorRelation.setDistributor_name("autotest"
						+ TestDataManager.randomStr(8));
				distributorRelation.setDistributor_phone(TestDataManager
						.getPhoneNum());
				distributorRelation.setDistributor_level_index(level);
				distributorRelation.setDistributor_status(0);
				distributorRelation
						.setParent_distributor_id(parent_distributor_id);

				// 如果agencyType=1，则是分销员机构，否则是CPS
				if (agencyType == 1) {
					distributorRelation.setDistributor_type(i == 0 ? 1 : 1001);
				} else
					distributorRelation.setDistributor_type(i == 0 ? 2 : 2001);

				distributorRelation.setAdd_time(YMTDateUtil.getDate());
				distributorRelation.setUpdate_time(YMTDateUtil.getDate());

				parent_distributor_id = distributorId;

				distributorRelationWrapper.insert(distributorRelation);

				distributorList.add(distributorId);
			}

			return distributorList;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ArrayList<Long>();
		}
	}

	public static void setDistributorConfig(Long merchantId, Integer layers,
			Boolean selfPurchaseCommission) throws ClientProtocolException,
			IOException {

		setDistributorConfig(merchantId, layers, selfPurchaseCommission, 1, null);
	}

	public static void setDistributorConfig(Long merchantId, Integer layers,
			Boolean selfPurchaseCommission, int userDistributorBindRuleType,
			Integer bindingEffectiveThreshold) throws ClientProtocolException,
			IOException {

		setDistributorConfig(merchantId, layers, selfPurchaseCommission,
				userDistributorBindRuleType, bindingEffectiveThreshold, false);
	}
	
	public static void setDistributorConfig(Long merchantId, Integer layers,
			Boolean selfPurchaseCommission, int userDistributorBindRuleType,
			Integer bindingEffectiveThreshold, Boolean isZero) throws ClientProtocolException,
			IOException {

		List<DistributorLevelCommissionConfigVo> commissionList = new ArrayList<DistributorLevelCommissionConfigVo>();

		for (int i = 0; i < layers; i++) {
			
			DistributorLevelCommissionConfigVo distributorLevelCommissionConfigVo = null;
			
			if (isZero) {
				distributorLevelCommissionConfigVo = DistributorLevelCommissionConfigVo
						.createStandardDistributorLevelCommissionConfig()
						.withDistributorLevelIndex(i)
						.withLayer1Rate(BigDecimal.ZERO)
						.withLayer2Rate(BigDecimal.ZERO)
						.withLayer3Rate(BigDecimal.ZERO);
			} else {

				distributorLevelCommissionConfigVo = DistributorLevelCommissionConfigVo
						.createStandardDistributorLevelCommissionConfig()
						.withDistributorLevelIndex(i)
						.withLayer1Rate(
								new BigDecimal(String
										.valueOf(0.073d - i * 0.005d)))
						.withLayer2Rate(
								new BigDecimal(String
										.valueOf(0.031d - i * 0.005d)))
						.withLayer3Rate(
								new BigDecimal(String
										.valueOf(0.015d - i * 0.005d)));

			}
			
			commissionList.add(distributorLevelCommissionConfigVo);
		}

		SetDistributionConfigReq setDistributionConfigReq = new SetDistributionConfigReq();
		SetDistributionConfigCall setDistributionConfigCall = new SetDistributionConfigCall();

		setDistributionConfigReq.setDistributionLayers(layers);
		setDistributionConfigReq.setDistributionSettlementDelayDays(0);
		setDistributionConfigReq
				.setDistributorLevelCommissionConfigVoList(commissionList);
		setDistributionConfigReq.setMerchantId(merchantId);
		setDistributionConfigReq
				.setSelfPurchaseCommission(selfPurchaseCommission);
		setDistributionConfigReq
				.setUserDistributorBindRuleType(userDistributorBindRuleType);
		setDistributionConfigReq
				.setBindingEffectiveThreshold(bindingEffectiveThreshold);

		setDistributionConfigCall.setData(setDistributionConfigReq);
		setDistributionConfigCall.callService();
	}

	/**
	 * 
	 * @param merchantId
	 * @param agencyType
	 * @param settlementWay
	 * @param settlementPeriodicityType
	 * @param delayDays
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void setDistributorAgencyConfig(
			Long merchantId,
			int agencyType,
			Integer settlementWay,
			Integer settlementPeriodicityType,
			Integer delayDays,
			DistributionAgencyLevelCommissionConfigVo distributorLevelCommissionConfigVo)
			throws ClientProtocolException, IOException {

		SetDistributionAgencyConfigReq setDistributionAgencyConfigReq = new SetDistributionAgencyConfigReq();
		SetDistributionAgencyConfigCall setDistributionAgencyConfigCall = new SetDistributionAgencyConfigCall();

		setDistributionAgencyConfigReq
				.setDistributionAgencyLevelCommissionConfigVos(Arrays
						.asList(distributorLevelCommissionConfigVo));
		setDistributionAgencyConfigReq
				.setDistributionSettlementDelayDays(delayDays);
		setDistributionAgencyConfigReq.setMerchantId(merchantId);
		setDistributionAgencyConfigReq.setSettlementWay(settlementWay);
		setDistributionAgencyConfigReq
				.setSettlementPeriodicityType(settlementPeriodicityType);
		setDistributionAgencyConfigReq.setAgencyType(agencyType);

		setDistributionAgencyConfigCall.setData(setDistributionAgencyConfigReq);
		setDistributionAgencyConfigCall.callService();
	}

	public static void setDistributorAgencyConfig(Long merchantId,
			int agencyType, Integer settlementWay,
			Integer settlementPeriodicityType, Integer delayDays)
			throws ClientProtocolException, IOException {

		DistributionAgencyLevelCommissionConfigVo distributorLevelCommissionConfigVo = DistributionAgencyLevelCommissionConfigVo
				.createStandardDistributorLevelCommissionConfig(agencyType);

		setDistributorAgencyConfig(merchantId, agencyType, settlementWay,
				settlementPeriodicityType, delayDays,
				distributorLevelCommissionConfigVo);
	}

	public static void setSubDistributorAgencyConfig(Long merchantId,
			Long distributorId, Integer distributorType)
			throws ClientProtocolException, IOException {

		AgencySubDistributorCommisionRateVo agencySubDistributorCommisionRateVo = AgencySubDistributorCommisionRateVo
				.createStandardAgencySubDistributorLevelCommissionRate();

		SetAgencyDistributorConfigReq setAgencyDistributorConfigReq = new SetAgencyDistributorConfigReq();
		SetAgencyDistributorConfigCall setAgencyDistributorConfigCall = new SetAgencyDistributorConfigCall();

		setAgencyDistributorConfigReq.setMerchantId(merchantId);
		setAgencyDistributorConfigReq.setDistributorType(distributorType);
		setAgencyDistributorConfigReq.setDistributorId(distributorId);
		setAgencyDistributorConfigReq
				.setAgencySubDistributorCommisionRates(Arrays
						.asList(agencySubDistributorCommisionRateVo));

		setAgencyDistributorConfigCall.setData(setAgencyDistributorConfigReq);
		setAgencyDistributorConfigCall.callService();
	}

	public static void updateDistributorStatus(Long distributorId) {

		distributorRelationWrapper.updateDistributorStatus(distributorId);
	}

	public static void updateConsumerStatus(Long merchantId, Long userId,
			Boolean isDeleted) {

		DistributorConsumerRelationWrapper distributorConsumerRelationWrapper = new DistributorConsumerRelationWrapper();

		distributorConsumerRelationWrapper
				.updateDeleteStatusByMerchantIdAndUserId(merchantId, userId,
						isDeleted);
	}

	/**
	 * 代购神器分销订单结算job
	 *
	 * @return
	 */
	public static void doDistributorSettlement() {

		YmatouEasyCall mchDetailCall = new YmatouEasyCall("", "POST", "JSON");

		mchDetailCall
				.setUrl("http://shenqisettlement.iapi.shop2cn.com/api/doDistributorSettlement");

		mchDetailCall.setData("{}");

		try {
			mchDetailCall.callService();

			Logger.comment(mchDetailCall.getReturnData());

		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	public static void saveInvitationMember(Long merchantId,
			List<Integer> levelIndexList) throws ClientProtocolException,
			IOException {

		// 绑定顶级分销员
		BindMerchantRootDistributorReq bindMerchantRootDistributorReq = new BindMerchantRootDistributorReq();

		bindMerchantRootDistributorReq.setMerchantId(merchantId);
		bindMerchantRootDistributorReq.setMerchantName(TestDataManager
				.getChineseName());
		bindMerchantRootDistributorReq.setMerchantPhone(TestDataManager
				.getPhoneNum());

		BindMerchantRootDistributorCall bindMerchantRootDistributorCall = new BindMerchantRootDistributorCall();

		bindMerchantRootDistributorCall.setData(bindMerchantRootDistributorReq);
		bindMerchantRootDistributorCall.callService();

		// 分销员自动审核为true
		SaveMerchantDistributorInviteConfigReq req = new SaveMerchantDistributorInviteConfigReq();

		req.setAutoAudit(true);

		if (null == levelIndexList)
			req.setLevelIndexList(Arrays.asList(0));
		else
			req.setLevelIndexList(levelIndexList);

		req.setMchId(merchantId);

		SaveMerchantDistributorInviteConfigCall saveInvitationMemberCall = new SaveMerchantDistributorInviteConfigCall();

		saveInvitationMemberCall.setData(req);
		saveInvitationMemberCall.callService();
	}

	public static void updateDistributorInfo(Long mchId, Long distributorId)
			throws ClientProtocolException, IOException {

		UpdateDistributorInfoReq req = new UpdateDistributorInfoReq();

		req.setMchId(mchId);
		req.setDistributorId(distributorId);
		req.setAvatarUrl("http://pic1.ymatou.com/G01/M00/41/2B/rBBlD1yYU-SAJhweAADmTO2YrBw085_1_1_o.jpg");
		req.setNickName("autotest" + TestDataManager.randomStr(8));

		UpdateDistributorInfoCall call = new UpdateDistributorInfoCall();

		call.setData(req);
		call.callService();
	}

	/**
	 * 创建一个自动审核分销员的商户
	 * 
	 * @param merchantId
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void createAutoAuditDistributor(Long merchantId)
			throws ClientProtocolException, IOException {

		// 商户设置分销员功能
		SqDistributorService.setDistributorConfig(merchantId, 1, false);

		// 商户设置自动审核分销员
		SqDistributorService.saveInvitationMember(merchantId, null);
	}

	public static void createDistributorApply(Long merchantId,
			Long distributorId, Long inviterId) throws ClientProtocolException,
			IOException {

		DistributorApplyReq distributorApplyReq = DistributorApplyReq
				.createStandardDistributorApply(merchantId)
				.withDistributorId(distributorId).withInviterId(inviterId);

		SqDistributorService.getDistributorApplyId(distributorApplyReq);
	}

	/**
	 * 创建自购用户
	 * 
	 * @param shopId
	 *            店主id
	 * @param isBindCs
	 *            是否绑定客服
	 * @return
	 * @throws Exception
	 */
	public static HashMap<String, Object> createSelfPurchaseUser(Long shopId,
			Boolean isBindCs) throws Exception {

		String mobile = TestDataManager.getPhoneNum();

		Integer duserId = SqDistributorService.createDUser(shopId, mobile)
				.intValue();
		Integer userId = SqDistributorService.createMemberUser(shopId)
				.intValue();

		// 将会员与店主绑定
		SqDistributorService
				.bindMobile(shopId, (long) userId, mobile, isBindCs);

		HashMap<String, Object> map = new HashMap<>();

		map.put("distributorId", duserId);
		map.put("userId", userId);
		map.put("mobile", mobile);

		return map;
	}

	/**
	 * 创建分销员类型的用户
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Long createDUser(Long shopId, String mobile) throws Exception {

		// 创建分销员
		UserCreateBean dusercreateBean = DGUserCallService.initUsercreateBean();
		dusercreateBean.setShopId(shopId.intValue());
		dusercreateBean.setMobile(mobile);
		dusercreateBean.setUserType(3);

		Integer duserId = DGUserCallService.UserCreateCall(dusercreateBean);

		return (long) duserId;
	}

	/**
	 * 创建会员
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Long createMemberUser(Long shopId) throws Exception {

		// 创建会员
		UserCreateBean usercreateBean = DGUserCallService.initUsercreateBean();
		Integer userId = DGUserCallService.UserCreateCall(usercreateBean);
		CreateMemberBean createMem = GodMemberService.initCreateMemberBean(
				shopId.intValue(), userId, usercreateBean.getOpenId());
		// 60.小程序 61.h5
		createMem.setAccessSource(0);
		GodMemberService.creatememberCall(createMem);

		return (long) userId;
	}

	/**
	 * 将会员与店主绑定
	 * 
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static void bindMobile(Long shopId, Long userId, String mobile,
			Boolean isBindCs) throws ClientProtocolException, IOException {

		// 将会员与店主绑定
		Integer csid = null;

		if (isBindCs)
			csid = 1;

		GodMemberService.bindMobile(shopId.intValue(), userId.intValue(),
				mobile, csid);
	}

	public static BriefMemberInfoResp getBriefMemberInfo(Long sellerId,
			Long userId) throws ClientProtocolException, IOException {

		BriefMemberInfoBean briefmemberinfoBean = new BriefMemberInfoBean();
		BriefMemberInfoCall briefmemberinfoCall = new BriefMemberInfoCall();

		briefmemberinfoBean.setShopId(sellerId.intValue());
		briefmemberinfoBean.setUserId(userId.intValue());

		briefmemberinfoCall.setData(briefmemberinfoBean);
		briefmemberinfoCall.callService();

		return briefmemberinfoCall.getBriefMemberInfoResp();
	}
	
	/**
	 * 获取连锁店主店
	 * @param mchId
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static Long getMasterShopId(Long mchId) throws Exception {

		Long masterShopId = 0L;
		
		getAllChainShopIdListBean bean = new getAllChainShopIdListBean();
		getAllChainShopIdListCall call = new getAllChainShopIdListCall();

		bean.setMchId(mchId.intValue());

		call.setData(bean);
		call.callService();
		
		JSONObject result = new JSONObject(call.getReturnData()).getJSONObject("result");
		
		JSONArray chainShopList = result.getJSONArray("chainShopList");
		
		if (null == chainShopList || chainShopList.length() == 0)
			return masterShopId;
		
		for (int i = 0; i < chainShopList.length(); i++) {
			
			JSONObject object = (JSONObject) chainShopList.get(i);
			
			if (object.getBoolean("master")) {
				
				masterShopId = object.getLong("shopId");
				
			} else
				break;
		}

		return masterShopId;
	}
	
	/**
	 * 设置商品分佣
	 * @param merchantId
	 * @param layers
	 * @param selfPurchaseCommission
	 * @param userDistributorBindRuleType
	 * @param bindingEffectiveThreshold
	 * @param isZero
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void saveProductCommission(Long merchantId, List<String> productIds,
			Boolean isDistributorCommission, int distributorLayers, Boolean isPartnerCommissions, Boolean isZero) throws ClientProtocolException,
			IOException {
		
		List<ProductCommission> productCommissions = new ArrayList<>();
		
		for (int i = 0; i < productIds.size(); i++) {
			
			ProductCommission productCommission = new ProductCommission();
			
			String productId = productIds.get(i);
			
			productCommission.setProductCode("productCode" + productId);
			productCommission.setProductId(productId);
			productCommission.setProductTitle("productTitle" + productId);
			
			productCommissions.add(productCommission);
		}
		
		List<DistributorCommission> distributorCommissions = new ArrayList<DistributorCommission>();

		for (int i = 0; i < distributorLayers; i++) {

			if (isDistributorCommission) {

				DistributorCommission distributorCommission = null;

				if (isZero) {
					distributorCommission = DistributorCommission
							.createStandardDistributorCommission()
							.withDistributorLevelIndex(i)
							.withLayer1Rate(BigDecimal.ZERO)
							.withLayer2Rate(BigDecimal.ZERO)
							.withLayer3Rate(BigDecimal.ZERO);
				} else {

					distributorCommission = DistributorCommission
							.createStandardDistributorCommission()
							.withDistributorLevelIndex(i)
							.withLayer1Rate(
									new BigDecimal(String
											.valueOf(0.0856d - i * 0.005d)))
							.withLayer2Rate(
									new BigDecimal(String
											.valueOf(0.063d - i * 0.005d)))
							.withLayer3Rate(
									new BigDecimal(String
											.valueOf(0.031d - i * 0.005d)));
				}

				distributorCommissions.add(distributorCommission);
			}
		}
		
		List<PartnerCommission> partnerCommissions = null;
		
		if (isPartnerCommissions) {

			partnerCommissions = new ArrayList<>();
			
			PartnerCommission partnerCommission = new PartnerCommission();
			
			if (isZero) {

				partnerCommission.setPartnerIndex(0);
				partnerCommission.setLayer1Rate(BigDecimal.ZERO);
				partnerCommission.setLayer2Rate(BigDecimal.ZERO);
			} else {

				partnerCommission.setPartnerIndex(0);
				partnerCommission.setLayer1Rate(new BigDecimal(String
						.valueOf(0.055d)));
				partnerCommission.setLayer2Rate(new BigDecimal(String
						.valueOf(0.027d)));
			}
			
			partnerCommissions.add(partnerCommission);
		}		

		SaveProductCommissionReq saveProductCommissionReq = new SaveProductCommissionReq();
		SaveProductCommissionCall saveProductCommissionCall = new SaveProductCommissionCall();

		saveProductCommissionReq.setMerchantId(merchantId);
		saveProductCommissionReq.setProductCommissions(productCommissions);
		saveProductCommissionReq.setDistributorCommissions(distributorCommissions);
		saveProductCommissionReq.setPartnerCommissions(partnerCommissions);

		saveProductCommissionCall.setData(saveProductCommissionReq);
		saveProductCommissionCall.callService();
	}
	
	public static void saveAgencyCategoryCommissionRate(Long merchantId)
			throws ClientProtocolException, IOException {

		ProductCategoryRateInsertReq productCategoryRateInsertReq = new ProductCategoryRateInsertReq();
		ProductCategoryRateInsertCall productCategoryRateInsertCall = new ProductCategoryRateInsertCall();

		ProductCategoryCommissionRateVo productCategoryCommissionRateVo = new ProductCategoryCommissionRateVo();

		productCategoryCommissionRateVo.setAgencyLevelIndex(0);
		productCategoryCommissionRateVo.setRate(new BigDecimal("0.13"));

		AgencyCategoryCommissionRateVo agencyCategoryCommissionRateVo = new AgencyCategoryCommissionRateVo();

		agencyCategoryCommissionRateVo.setFirstCategoryId(1001L);
		agencyCategoryCommissionRateVo.setSecondCategoryId(1002L);
		agencyCategoryCommissionRateVo
				.setProductCategoryCommissionRateVos(Arrays
						.asList(productCategoryCommissionRateVo));

		productCategoryRateInsertReq.setAgencyCommissionRate(Arrays
				.asList(agencyCategoryCommissionRateVo));
		productCategoryRateInsertReq.setMerchantId(merchantId);

		productCategoryRateInsertCall.setData(productCategoryRateInsertReq);
		productCategoryRateInsertCall.callService();
	}
	
	public static void setDistributorSettlementConfig(long shopId, int value)
			throws ClientProtocolException, IOException {

		setBizConfigBean bean = new setBizConfigBean();
		setBizConfigCall call = new setBizConfigCall();

		String key = "distributor_settlement_cur";

		HashMap<String, String> map = new HashMap<>();
		map.put(key, String.valueOf(value));

		bean.setBizId((int) shopId);
		bean.setBizConfigMap(map);

		call.setData(bean);
		call.callService();
	}

	public static void main(String[] args) throws Exception {

		// SqDistributorService.buildSqDistributorRelation(31234, 0, 3, 0);
//		AgentProductBean productBean = DGSQBuildProxyChainCallService
//				.createProxychain((int) 500002490, 1, false, false);
//		SqDistributorService.createSelfPurchaseUser(productBean.getSellerId(),
//				false);
		
//		System.out.println(SqDistributorService.getMasterShopId(501742451L));
		
		SqDistributorService.saveAgencyCategoryCommissionRate(501742451L);

		// SqDistributorService.bindDistributorConsumerRelation(25779637L,
		// 501150335L, 25779639L);
		// SqDistributorService.setDistributorConfig(501150335L, 2, false);

		// SqDistributorService.createAutoAuditDistributor(5009188900L);
		// System.out.println(String.valueOf(0.1556 + 1 * 0.1));
	}
}
